﻿using System;
using System.Configuration;
using System.Web.Mvc;
using Newtonsoft.Json;
using WikeSoft.Core;
using WikeSoft.Core.Extension;
using WikeSoft.Core.License;
using WikeSoft.Core.Security;

namespace WikeSoft.Web
{
    public class LisenceKeyFilter : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            string lisenceKey =  ConfigurationManager.AppSettings["licensekey"];
            if (lisenceKey.IsBlank())
            {
                ViewResult result = new ViewResult();
                result.ViewName = "LicenseKey";
                filterContext.Result = result;
            }
            else
            {
                try
                {
                    string str = DesEncrypt.Decode(lisenceKey);
                    LicenseEntity entity = JsonConvert.DeserializeObject<LicenseEntity>(str);
                    string mac = Mac.GetMacAddressByWmi();
                    string key = DesEncrypt.Encode(mac);
                    if (entity.ExpireDate.AddDays(1) < DateTime.Now || key != entity.Key)
                    {
                        ViewResult result = new ViewResult();
                        result.ViewName = "LicenseKey";
                        filterContext.Result = result;
                    }
                }
                catch  
                {
                    ViewResult result = new ViewResult();
                    result.ViewName = "LicenseKey";
                    filterContext.Result = result;
                }


            }
        }
    }
}